package pl.ptemich.tankwars.tools;

import pl.ptemich.nov2k13.engine.AxialCoordinate;
import pl.ptemich.nov2k13.engine.CubeCooridnate;
import pl.ptemich.nov2k13.engine.EngineException;
import pl.ptemich.nov2k13.engine.HexBoard.HexType;
import pl.ptemich.nov2k13.engine.OffsetCooridinate;

public class HexTools {

  public static OffsetCooridinate getOffsetCoordinate(int tableX, int tableY, HexType hexType) {
    switch (hexType) {
    case FLAT_ORIENTATION:
      return new OffsetCooridinate(tableX, tableY);
    case POINTY_ORIENTATION:
      return new OffsetCooridinate(tableX, tableY);
    }
    throw new EngineException("Unknown HEX type " + hexType);
  }


  public static AxialCoordinate getAxialCoordinate(CubeCooridnate cubeCooridnate) {
    return new AxialCoordinate(cubeCooridnate.x, cubeCooridnate.z);
  }
  
  /**
  * # convert odd-q offset to cube
  * x = c
  * z = r - (c - (c&1)) / 2
  * y = -x-z
  **/
  public static CubeCooridnate getCubeCoordinate(OffsetCooridinate offsetCoordinate) {
    int z = offsetCoordinate.r - (offsetCoordinate.c - (offsetCoordinate.c & 1)) / 2;
    return new CubeCooridnate(offsetCoordinate.c, - offsetCoordinate.c - z, z);
  }
  
  
  /**
   * # convert axial to cube
   * x = x
   * z = y
   * y = -x-z
   */
  public static CubeCooridnate getCubeCoordinate(AxialCoordinate axialCoordinate) {
    return new CubeCooridnate(axialCoordinate.x, -axialCoordinate.x - axialCoordinate.y , axialCoordinate.y);
  }
  
  
  /**
   * # convert cube to odd-q offset
   * q = x
   * r = z + (x - (x&1)) / 2
   */
  public static OffsetCooridinate getOffsetCoordinate(CubeCooridnate cubeCoordinate) {
    return new OffsetCooridinate(cubeCoordinate.x, 
                                 cubeCoordinate.z + (cubeCoordinate.x - (cubeCoordinate.x & 1)) / 2);
  }
  
  
  public static int getDistance(OffsetCooridinate hex1, OffsetCooridinate hex2) {
    CubeCooridnate cube1 = hex1.getCubeCoordinate();
    CubeCooridnate cube2 = hex2.getCubeCoordinate();
    return (Math.abs(cube1.x - cube2.x) + Math.abs(cube1.y - cube2.y) + Math.abs(cube1.z - cube2.z)) / 2;
  }
}
